import MyFormUploadButton from '@/components/MyFormUploadButton';
import {
  createDeviceType,
  getDeviceTypeDetails,
  updateDeviceType,
} from '@/services/api/deviceType';
import { DeviceTypeResultItem } from '@/services/api/model/deviceTypeModel';
import { PlusOutlined } from '@ant-design/icons';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import React from 'react';
type CreateFormProps = {
  onCancel?: () => void;
  onSubmit: (values: DeviceTypeResultItem) => void;
  deviceTypeToken?: string;
  title?: string;
  trigger?: JSX.Element;
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const {
    onSubmit,
    deviceTypeToken,
    title = '添加',
    trigger = (
      <Button type="primary">
        <PlusOutlined />
        {title}
      </Button>
    ),
  } = props;
  const onOpenChange = () => {};

  return (
    <ModalForm<DeviceTypeResultItem>
      request={async () => {
        if (deviceTypeToken) {
          const res = await getDeviceTypeDetails({ includeAsset: true, token: deviceTypeToken });

          return res;
        } else {
          return {};
        }
      }}
      title={`${title}设备`}
      modalProps={{
        // 关闭弹框是否销毁 (相当于直接进行了表单重置)
        destroyOnClose: true,
      }}
      trigger={trigger}
      onOpenChange={() => onOpenChange()}
      onFinish={async (values) => {
        console.log(values);
        if (!deviceTypeToken) {
          await createDeviceType({
            ...values,
          });
        } else {
          await updateDeviceType({
            ...values,
            token: deviceTypeToken,
          });
        }

        onSubmit(values);
        message.success('提交成功');
        // 返回true 则关闭
        return true;
      }}
      initialValues={{}}
    >
      <ProFormText
        label="Token"
        name="token"
        rules={[
          {
            required: true,
            message: '请输入Token',
          },
        ]}
        placeholder="请输入Token"
      />

      <ProFormText
        label="名称"
        name="name"
        rules={[
          {
            required: true,
            message: '请输入名称',
          },
        ]}
        placeholder="请输入名称"
      />
      <ProFormSelect
        label="接入类型"
        name="containerPolicy"
        options={[
          {
            label: '上位机接入',
            value: '1',
          },
          {
            label: 'PLC接入',
            value: '2',
          },
          {
            label: '改造接入',
            value: '3',
          },
        ]}
      />
      <Form.Item
        name="imageUrl"
        label="图片"
        rules={[
          {
            required: false,
            message: '请上传',
          },
        ]}
      >
        <MyFormUploadButton></MyFormUploadButton>
      </Form.Item>

      <ProFormTextArea label="备注" name="description" placeholder="请输入备注" />
    </ModalForm>
  );
};

export default CreateForm;
